package registry

import (
	"context"
	"fmt"
	"testing"
	"time"

	"github.com/lukeaxu/discover"
	"github.com/lukeaxu/discover/proto/gen"
	"github.com/lukeaxu/discover/registry/etcd"
	"github.com/stretchr/testify/require"
	clientv3 "go.etcd.io/etcd/client/v3"
)

type UserServiceServer struct {
	Resp *gen.GetByIdResp
	gen.UnimplementedUserServiceServer
}

func (s UserServiceServer) GetById(ctx context.Context, req *gen.GetByIdReq) (*gen.GetByIdResp, error) {
	return s.Resp, nil
}

func EstablishServerWithRegistry(t *testing.T, port int, sn string, resp *gen.GetByIdResp) {
	// for i, resp := range resps {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	})
	require.NoError(t, err)
	defer cli.Close()

	r, err := etcd.NewRegistry(cli, etcd.WithLeaseTTL(3))
	require.NoError(t, err)
	server, err := discover.NewServer(sn, discover.WithRegistry(r))
	require.NoError(t, err)
	gen.RegisterUserServiceServer(server, &UserServiceServer{Resp: resp})

	if err := server.Start(fmt.Sprintf(":%d", port)); err != nil {
		t.Log(err)
	}
}
